package com.qfedu.web.common;

import com.qfedu.web.servlet.UserServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/3 9:19
 * 描述:
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        //通过反射的方式找到要执行的方法 (this：表示当前引用对象   表示的是 UserServlet || OrderServlet)
        Class clazz = this.getClass();

        try {
            //根据方法名， 参数列表获取 对应的方法
            Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //设置 私有方法 可用
            declaredMethod.setAccessible(true);
            //调用(真实)方法， result 就是真实方法的返回
            Object result = declaredMethod.invoke(this, req, resp);
            resp.setCharacterEncoding("utf-8");
            //处理结果
            if(result != null) {
                String res = (String) result;
                if(res.startsWith("redirect")) {
                    res = res.replace("redirect:", "");
                    resp.sendRedirect(res);
                }else if(res.startsWith("forward")) {
                    res = res.replace("forward:", "");
                    req.getRequestDispatcher(res).forward(req, resp);
                }else {
                    resp.getWriter().write(res);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            System.out.println("找不到方法");
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            System.out.println("调用方法失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    protected String test(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return null;
    }

}
